// ================================================================================
// 		File: PartyForum.cs
// 		Desc: 
//  
// 		Called by:   
//               
// 		Auth: chenwenzhi（）
// 		Date: 2016-05-05 21:55
// ================================================================================
// 		Change History
// ================================================================================
// 		Date:		Author:				Description:
// 		--------	--------			-------------------
//    
// ================================================================================
// 
// ================================================================================
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using ZHDJ.Core;
using ZHDJ.Core.Log;
using ZHDJ.Data.BLL;

namespace ZHDJ.Data.Models.Forum
{
    /// <summary>
    /// 帖子
    /// </summary>   
    public class PartyForum : EntityBase
    {
        #region 属性


        /// <summary>
        /// 类型
        /// </summary>
        public string ForumCategory { get; set; }

        /// <summary>
        /// 标题
        /// </summary>
        public string ForumTitle { get; set; }

        /// <summary>
        /// 内容
        /// </summary>
        public string ForumContent { get; set; }

        /// <summary>
        /// 访问次数
        /// </summary>
        public int? VisitTimes { get; set; }

        /// <summary>
        /// 今天访问次数
        /// </summary>
        public int? TodayVisitTimes { get; set; }

        /// <summary>
        /// 回帖数
        /// </summary>
        public int? ReplyCount { get; set; }

        /// <summary>
        /// 发帖人ID
        /// </summary>
        public string Author { get; set; }

        /// <summary>
        /// 发帖人
        /// </summary>
        public string AuthorName { get; set; }

        /// <summary>
        /// 发帖时间
        /// </summary>
        public DateTime? CreateTime { get; set; }

        /// <summary>
        /// 修改时间
        /// </summary>
        public DateTime? ModifyTime { get; set; }

        /// <summary>
        /// 统计更新时间
        /// </summary>
        public DateTime? StatisticTime { get; set; }

        /// <summary>
        /// 回复人ID
        /// </summary>
        public string ReplyBy { get; set; }

        /// <summary>
        /// 回复人
        /// </summary>
        public string ReplyByName { get; set; }

        /// <summary>
        /// 今天回复次数
        /// </summary>
        public int? TodayReplyTimes { get; set; }

        /// <summary>
        /// 最新回复时间
        /// </summary>
        public DateTime? ReplyTime { get; set; }

        /// <summary>
        /// 置顶
        /// </summary>
        public int? IsFirst { get; set; }

        /// <summary>
        /// 置顶时间
        /// </summary>
        public DateTime? IsFirstTime { get; set; }

        /// <summary>
        /// 精华
        /// </summary>
        public int? IsEssence { get; set; }

        /// <summary>
        /// 精华时间
        /// </summary>
        public DateTime? IsEssenceTime { get; set; }

        /// <summary>
        /// 版块
        /// </summary>
        public string TypeID { get; set; }

        /// <summary>
        /// 聚焦
        /// </summary>
        public int? IsFocus { get; set; }

        /// <summary>
        /// 聚焦时间
        /// </summary>
        public DateTime? IsFocusTime { get; set; }

        /// <summary>
        /// 数据来源（网站，app）
        /// </summary>
        public int? Source { get; set; }

        #endregion

        #region 查询管理

        public static DataSet GetGridData(int pageIndex, int pageSize, string searchKey, string typeId = "",
            SysEnum.ForumOrderby orderby = SysEnum.ForumOrderby.NewForum, bool isAll = true)
        {
            var parameters = new List<MySqlParameter>()
            {
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "Begin", Value = (pageIndex)*pageSize},
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "PageSize", Value = pageSize}
            };


            var sb = new StringBuilder();
            sb.Append(@"select SQL_CALC_FOUND_ROWS  data.*,t.Title
                        from tblPartyForum data
                        left join tblPartyForumtype t on(t.id=data.typeid)
                        where 1=1 ");
            if (!string.IsNullOrEmpty(searchKey))
            {
                sb.Append(" and ( data.ForumTitle like ?searchKey  or data.AuthorName like ?searchKey) ");
                parameters.Add(new MySqlParameter()
                {
                    DbType = DbType.String,
                    ParameterName = "searchKey",
                    Value = string.Format("%{0}%", searchKey)
                });
            }
            if (!string.IsNullOrEmpty(typeId))
            {
                sb.Append(" and data.typeId like ?typeId ");
                parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "typeId", Value = typeId});
            }
            if (!isAll)
            {
                sb.Append(GetForumWhereSql(orderby));
            }
            sb.AppendFormat(" order by {0} LIMIT ?Begin ,?PageSize;SELECT FOUND_ROWS();",
                GetForumOrderbySql(orderby, !string.IsNullOrEmpty(typeId)));
            return MySqlHelper.ExecuteDataSet(sb.ToString(), parameters.ToArray());
        }

        /// <summary>
        /// 获取条件sql
        /// </summary>
        /// <param name="orderby"></param>
        /// <param name="isType">是否版块数据</param>
        /// <returns></returns>
        private static string GetForumWhereSql(SysEnum.ForumOrderby orderby)
        {
            var sql = "";
            switch (orderby)
            {

                case SysEnum.ForumOrderby.Best:
                    sql = "and data.IsEssence = 1 ";
                    break;


                case SysEnum.ForumOrderby.Focus:
                    sql = "and data.IsFocus = 1 ";
                    break;
            }
            return sql;

        }

        /// <summary>
        /// 获取排序sql
        /// </summary>
        /// <param name="orderby"></param>
        /// <param name="isType">是否版块数据</param>
        /// <returns></returns>
        private static string GetForumOrderbySql(SysEnum.ForumOrderby orderby, bool isType)
        {
            var list = new List<string>();
            if (isType)
            {
                list.Add("data.IsFirst desc");
            }
            switch (orderby)
            {
                case SysEnum.ForumOrderby.NewForum:
                    list.Add("data.CreateTime desc");
                    break;
                case SysEnum.ForumOrderby.NewReply:
                    list.Add("data.ReplyTime desc");
                    break;
                case SysEnum.ForumOrderby.Best:
                    list.Add("data.IsEssenceTime desc");
                    break;
                case SysEnum.ForumOrderby.VisitTimes:
                    list.Add("data.VisitTimes desc");
                    break;
                case SysEnum.ForumOrderby.TodayReplyTimes:
                    list.Add("data.TodayReplyTimes desc");
                    break;
                case SysEnum.ForumOrderby.TodayVisitTimes:
                    list.Add("data.TodayVisitTimes desc");
                    break;
                case SysEnum.ForumOrderby.Focus:
                    list.Add("data.IsFocusTime desc");
                    break;
            }
            return string.Join(",", list.ToArray());

        }

        /// <summary>
        /// 获取版块大分类
        /// </summary>
        /// <returns></returns>
        public static DataSet GetForumType(string parentId = "")
        {

            var parameters = new List<MySqlParameter>();
            var sb = new StringBuilder();

            sb.Append(@"select PT.*,
                        ifnull(s.TodayForumCount,0) TodayForumCount,
                        ifnull(s.TodayPostCount,0) TodayPostCount,
                        ifnull(s.ForumCount,0) ForumCount,  
                        ifnull(s.PostCount,0) PostCount ,
                        ifnull(s.NewForumTitle,'') NewForumTitle,
                        ifnull(s.NewForumID,'') NewForumID  
                        from tblPartyForumType PT
                        left join tblpartyforumtypestatistics s  on(s.id=PT.id)
                        where 
                        IFNULL(PT.IsShowIndex,0)=1");
            if (string.IsNullOrEmpty(parentId))
            {
                sb.Append(
                    " and  PT.ID in (select ParentID from tblPartyForumType tt1 where  IFNULL(tt1.IsShowIndex,0)=1)  ");
            }
            sb.Append(" and ifnull(PT.ParentID,'')=?ParentID  ");
            parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "ParentID", Value = parentId});

            sb.Append(" order by OrderNO ");
            return MySqlHelper.ExecuteDataSet(sb.ToString(), parameters.ToArray());
        }

        /// <summary>
        /// 获取版块大分类
        /// </summary>
        /// <returns></returns>
        public static DataTable GetOneForumType(string typeId)
        {
            var parameters = new List<MySqlParameter>();
            var sb = new StringBuilder();

            sb.Append(@"select PT.*,
                        ifnull(s.TodayForumCount,0) TodayForumCount,
                        ifnull(s.TodayPostCount,0) TodayPostCount,
                        ifnull(s.ForumCount,0) ForumCount,
                        ifnull(s.TodayForumCount,0) TodayForumCount,  
                        ifnull(s.PostCount,0) PostCount ,
                        ifnull(s.NewForumTitle,'') NewForumTitle,
                        ifnull(s.NewForumID,'') NewForumID  
                        from tblPartyForumType PT
                        left join tblpartyforumtypestatistics s  on(s.id=PT.id)
                        where 
           
                        IFNULL(PT.IsShowIndex,0)=1");

            sb.Append(" and ifnull(PT.Id,'')=?typeId  ");


            parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "typeId", Value = typeId});

            return MySqlHelper.ExecuteDataTable(sb.ToString(), parameters.ToArray());
        }

        /// <summary>
        /// 获取版主名
        /// </summary>
        /// <param name="typeID"></param>
        /// <returns></returns>
        public static string GetForumAdminName(string typeID)
        {
            string name = "";
            DataSet ds = GetForumAdmin(typeID);
            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    if (string.IsNullOrEmpty(name))
                    {
                        name = dr["UserName"].ToString();
                    }
                    else
                    {
                        name += "," + dr["UserName"].ToString();
                    }

                }
            }
            return name;
        }

        /// <summary>
        /// 获取版主
        /// </summary>
        /// <param name="typeID"></param>
        /// <returns></returns>
        public static DataSet GetForumAdmin(string typeId)
        {

            var parameters = new List<MySqlParameter>();
            var sql = @"select m.*,ad.TypeID from  tblPartyForumTypeAdmin ad 
                                                    left join tblPartyOrgMember m  on (ad.LoginID=m.LoginID )      
                                                    where ad.TypeID=?typeID order by LoginID";
            parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "typeID", Value = typeId});

            return MySqlHelper.ExecuteDataSet(sql, parameters.ToArray());
        }

        /// <summary>
        /// 我的帖
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchKey"></param>
        /// <param name="loginId"></param>
        /// <param name="orderby"></param>
        /// <param name="isAll"></param>
        /// <returns></returns>
        public static DataSet GetMyForum(int pageIndex, int pageSize, string searchKey, string loginId = "",
            SysEnum.ForumOrderby orderby = SysEnum.ForumOrderby.NewForum, bool isAll = true)
        {
            var parameters = new List<MySqlParameter>()
            {
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "Begin", Value = (pageIndex)*pageSize},
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "PageSize", Value = pageSize}
            };


            var sb = new StringBuilder();
            sb.Append(@"select SQL_CALC_FOUND_ROWS  data.*,t.Title
                        from tblPartyForum data
                        left join tblPartyForumtype t on(t.id=data.typeid)
                        where 1=1 ");
            if (!string.IsNullOrEmpty(searchKey))
            {
                sb.Append(" and ( data.ForumTitle like ?searchKey  ) ");
                parameters.Add(new MySqlParameter()
                {
                    DbType = DbType.String,
                    ParameterName = "searchKey",
                    Value = string.Format("%{0}%", searchKey)
                });
            }

            sb.Append(" and data.Author = ?Author ");
            parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "Author", Value = loginId});

            if (!isAll)
            {
                sb.Append(GetForumWhereSql(orderby));
            }
            sb.AppendFormat(" order by {0} LIMIT ?Begin ,?PageSize;SELECT FOUND_ROWS();",
                GetForumOrderbySql(orderby, true));
            return MySqlHelper.ExecuteDataSet(sb.ToString(), parameters.ToArray());
        }

        /// <summary>
        /// 我的回帖
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchKey"></param>
        /// <param name="loginId"></param>
        /// <param name="orderby"></param>
        /// <param name="isAll"></param>
        /// <returns></returns>
        public static DataSet GetMyReply(int pageIndex, int pageSize, string searchKey, string loginId = "",
            SysEnum.ForumOrderby orderby = SysEnum.ForumOrderby.NewForum, bool isAll = true)
        {
            var parameters = new List<MySqlParameter>()
            {
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "Begin", Value = (pageIndex)*pageSize},
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "PageSize", Value = pageSize}
            };
            var sb = new StringBuilder();
            sb.Append(@"select SQL_CALC_FOUND_ROWS  data.*,t.Title
                        from tblPartyForum data
                        left join tblPartyForumtype t on(t.id=data.typeid)
                        
                        where data.id in (select ForumID from tblpartyforumreply r where r.ReplyBy=?LoginId)");
            parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "LoginId", Value = loginId});
            if (!string.IsNullOrEmpty(searchKey))
            {
                sb.Append(" and ( data.ForumTitle like ?searchKey  ) ");
                parameters.Add(new MySqlParameter()
                {
                    DbType = DbType.String,
                    ParameterName = "searchKey",
                    Value = string.Format("%{0}%", searchKey)
                });
            }

            if (!isAll)
            {
                sb.Append(GetForumWhereSql(orderby));
            }
            sb.AppendFormat(" order by {0} LIMIT ?Begin ,?PageSize;SELECT FOUND_ROWS();",
                GetForumOrderbySql(orderby, true));
            return MySqlHelper.ExecuteDataSet(sb.ToString(), parameters.ToArray());
        }

        /// <summary>
        /// 我的访问
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchKey"></param>
        /// <param name="loginId"></param>
        /// <param name="orderby"></param>
        /// <param name="isAll"></param>
        /// <returns></returns>
        public static DataSet GetMyBrowse(int pageIndex, int pageSize, string searchKey, string loginId = "",
            SysEnum.ForumOrderby orderby = SysEnum.ForumOrderby.NewForum, bool isAll = true)
        {
            var parameters = new List<MySqlParameter>()
            {
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "Begin", Value = (pageIndex)*pageSize},
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "PageSize", Value = pageSize}
            };
            var sb = new StringBuilder();
            sb.Append(@"select SQL_CALC_FOUND_ROWS  data.*,t.Title
                        from tblPartyForum data
                        left join tblPartyForumtype t on(t.id=data.typeid)
                        
                        where data.id in (select ForumID from tblpartyforumbrowse b where b.BrowseUserID=?LoginId)");
            parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "LoginId", Value = loginId});
            if (!string.IsNullOrEmpty(searchKey))
            {
                sb.Append(" and ( data.ForumTitle like ?searchKey  or data.AuthorName like ?searchKey) ");
                parameters.Add(new MySqlParameter()
                {
                    DbType = DbType.String,
                    ParameterName = "searchKey",
                    Value = string.Format("%{0}%", searchKey)
                });
            }

            if (!isAll)
            {
                sb.Append(GetForumWhereSql(orderby));
            }
            sb.AppendFormat(" order by {0} LIMIT ?Begin ,?PageSize;SELECT FOUND_ROWS();",
                GetForumOrderbySql(orderby, true));
            return MySqlHelper.ExecuteDataSet(sb.ToString(), parameters.ToArray());
        }

        /// <summary>
        /// 我的精华
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchKey"></param>
        /// <param name="loginId"></param>
        /// <param name="orderby"></param>
        /// <param name="isAll"></param>
        /// <returns></returns>
        public static DataSet GetMyEssence(int pageIndex, int pageSize, string searchKey, string loginId = "",
            SysEnum.ForumOrderby orderby = SysEnum.ForumOrderby.Best, bool isAll = true)
        {
            var parameters = new List<MySqlParameter>()
            {
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "Begin", Value = (pageIndex)*pageSize},
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "PageSize", Value = pageSize}
            };
            var sb = new StringBuilder();
            sb.Append(@"select SQL_CALC_FOUND_ROWS  data.*,t.Title
                        from tblPartyForum data
                        left join tblPartyForumtype t on(t.id=data.typeid)
                        where data.Author = ?LoginId ");
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "LoginId", Value = loginId });
            if (!string.IsNullOrEmpty(searchKey))
            {
                sb.Append(" and ( data.ForumTitle like ?searchKey  or data.AuthorName like ?searchKey) ");
                parameters.Add(new MySqlParameter()
                {
                    DbType = DbType.String,
                    ParameterName = "searchKey",
                    Value = string.Format("%{0}%", searchKey)
                });
            }

            if (!isAll)
            {
                sb.Append(GetForumWhereSql(orderby));
            }
            sb.AppendFormat(" order by {0} LIMIT ?Begin ,?PageSize;SELECT FOUND_ROWS();",
                GetForumOrderbySql(orderby, true));
            return MySqlHelper.ExecuteDataSet(sb.ToString(), parameters.ToArray());
        }

        /// <summary>
        /// 根据帖ID，找回复和帖
        /// </summary>
        /// <param name="forumID"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static DataSet GetForumInfoByID(string forumID, int pageIndex, int pageSize)
        {
            var parameters = new List<MySqlParameter>()
            {
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "Begin", Value = (pageIndex)*pageSize},
                new MySqlParameter() {DbType = DbType.Int32, ParameterName = "PageSize", Value = pageSize},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "ForumID", Value = forumID}

            };
            string sql = @" select SQL_CALC_FOUND_ROWS  a.*,b.UserName from ( 
                    select ID,ForumTitle,ForumContent,Author,CreateTime,Source,'0' as 'IsTpoic', ifnull(IsEssence,0) IsEssence,ifnull(IsFirst,0) IsFirst,ifnull(IsFocus,0) IsFocus
                    from tblPartyForum where ID=?ForumID
                    union
                    select ID ,'',ReplyContent,ReplyBy,ReplyTime,Source,'1' as 'IsTpoic' ,0,0,0
                    from tblPartyForumReply where  ForumID=?ForumID
                    )as a 
										left join tblPartyOrgMember as b on a.Author = b.LoginID 
                    where ifnull(a.Author,'')<>'' 
										order by a.CreateTime  LIMIT ?Begin ,?PageSize;SELECT FOUND_ROWS();  ";

            return MySqlHelper.ExecuteDataSet(sql, parameters.ToArray());

        }

        public static DataTable GetUserInfo(string loginId)
        {
            var parameters = new List<MySqlParameter>();
            string sql = string.Empty;
            sql = @"select US.CreateTime,BranchName,fui.ImageID BBSImage,fui.NickName BBSUserName,
                        (select IfNULL(SUM(Score),0) from tblPartyObjectScore where Category like 'Forum%'  and ObjectID=us.LoginID)ScoreNum,
                        (select IfNULL(Level,0) from tblpartyforumuserinfo ss where ss.LoginID=US.LoginID) LevelNum,
                        (select COUNT(1) from tblPartyForum where Author=us.LoginID)PostNum ,
                        (select COUNT(1) from tblPartyForum where Author=us.LoginID and IsEssence=1)JinHuaNum ,
                        (select COUNT(1) from tblPartyForumBrowse where BrowseUserID=us.loginID)BrowseNum,
                        (select COUNT(1) from tblPartyForumReply where ReplyBy =us.LoginID)ReplyCount
from tblPartyOrgMember  US
                        left join tblPartyForumUserInfo   fui on(fui.LoginID=us.loginID)
                        left join tblPartyOrgBranch org on US.BranchID=org.BranchID
                        where us.LoginID=?loginID";
            parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "loginID", Value = loginId});

            return MySqlHelper.ExecuteDataTable(sql, parameters.ToArray());

        }

        /// <summary>
        /// 删除帖子
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isReply"></param>
        /// <returns></returns>
        public static bool DeleteForum(string id, bool isReply, string createBy)
        {
            var parameters = new List<MySqlParameter>();
            string sql = string.Empty;
            if (isReply)
            {
                sql = "delete from tblPartyForumReply where ID=?ID;";
            }
            else
            {
                sql = "delete from tblPartyForum where ID=?ID;";
                sql += "delete from tblPartyForumReply where ForumID=?ID;";
            }
            parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "ID", Value = id});

            if (MySqlHelper.ExecuteNonQuery(sql, parameters.ToArray()) > 0)
            {
                if (isReply)
                {
                    var forumId = "";
                    var loginId = "";
                    using (var DB = new DBInstance().DB)
                    {
                        var reply = DB.PartyForumReplys.Find(id);
                        if (reply == null)
                        {
                            return false;
                        }
                        forumId = reply.ForumID;
                        loginId = reply.ReplyBy;
                    }
                    PartyScoreHelper.Add(
                        () => PartyScoreHelper.AddForum(SysEnum.ForumScoreType.DeleteReply, loginId, createBy, forumId));
                }
                else
                {
                    var author = "";
                    using (var DB = new DBInstance().DB)
                    {
                        var forum = DB.PartyForums.Find(id);
                        if (forum == null)
                        {
                            return false;
                        }
                        author = forum.Author;
                    }

                    PartyScoreHelper.Add(
                        () => PartyScoreHelper.AddForum(SysEnum.ForumScoreType.Delete, author, createBy, id));
                }
            }
            return false;
        }

        /// <summary>
        /// 设置精华帖子
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isJinHua"></param>
        /// <returns></returns>
        public static bool SetJinHuaForum(string id, bool isJinHua,  string createBy)
        {
            var author = "";
            using (var DB = new DBInstance().DB)
            {
                var forum = DB.PartyForums.Find(id);
                if (forum == null)
                {
                    return false;
                }
                author = forum.Author;
            }
            
            var parameters = new List<MySqlParameter>();
            string sql = string.Empty;
            bool result = false;
            if (isJinHua)
            {
                sql =
                    string.Format(
                        "update tblPartyForum set IsEssence=1,IsEssenceTime=?IsEssenceTime where ID=?ForumID; ");

                parameters.Add(new MySqlParameter()
                {
                    DbType = DbType.String,
                    ParameterName = "IsEssenceTime",
                    Value = DateTime.Now
                });
                parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "ForumID", Value = id});

            }
            else
            {
                sql = string.Format("update tblPartyForum set IsEssence=0,IsEssenceTime=null where ID=?ForumID ");
                parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "ForumID", Value = id});

            }
            result = MySqlHelper.ExecuteNonQuery(sql, parameters.ToArray()) > 0;
            if (result)
            {
                // 加积分
                if (isJinHua)
                {
                    PartyScoreHelper.Add(
                        () => PartyScoreHelper.AddForum(SysEnum.ForumScoreType.Essence, author, createBy, id));
                }
                else
                {
                    PartyScoreHelper.Add(
                        () => PartyScoreHelper.AddForum(SysEnum.ForumScoreType.CancelEssence, author, createBy, id));
                }
            }
            return result;
        }


        /// <summary>
        /// 设置置顶
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isFirst"></param>
        /// <returns></returns>
        public static bool SetTopForum(string id, bool isFirst, string createBy)
        {
            var author = "";
            using (var DB = new DBInstance().DB)
            {
                var forum = DB.PartyForums.Find(id);
                if (forum == null)
                {
                    return false;
                }
                author = forum.Author;
            }
            var parameters = new List<MySqlParameter>();
            string sql = string.Empty;
            if (isFirst)
            {
                sql =
                    string.Format("update tblPartyForum set IsFirst=1,IsFirstTime=?IsFirstTime where ID=?ForumID ");
                parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "IsFirstTime", Value = DateTime.Now});
                parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "ForumID", Value = id});
            }
            else
            {
                sql = string.Format("update tblPartyForum set IsFirst=0,IsFirstTime=null where ID=@ForumID ");
                parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "ForumID", Value = id});

            }

            if (MySqlHelper.ExecuteNonQuery(sql, parameters.ToArray()) > 0)
            {
                // 加积分
                if (isFirst)
                {
                    PartyScoreHelper.Add(
                        () => PartyScoreHelper.AddForum(SysEnum.ForumScoreType.First, author,  createBy, id));
                }
                else
                {
                    PartyScoreHelper.Add(
                        () => PartyScoreHelper.AddForum(SysEnum.ForumScoreType.CancelFirst, author, createBy, id));
                }
                return true;
            }
            return false;
        }


        /// <summary>
        /// 聚焦 为2时，
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isFocus"></param>
        /// <param name="createBy">创建人</param>
        /// <returns></returns>
        public static bool SetJuJiaoForum(string id, string isFocus,string createBy)
        {
            var author = "";
            using (var DB = new DBInstance().DB)
            {
                var forum = DB.PartyForums.Find(id);
                if (forum == null)
                {
                    return false;
                }
                author = forum.Author;
            }
            var parameters = new List<MySqlParameter>();
            string sql = string.Empty;
            if (isFocus == "1")
            {
                sql = string.Format("update tblPartyForum set IsFocus=1,IsFocusTime=?IsFocusTime where ID=?ForumID ");
                parameters.Add(new MySqlParameter()
                {
                    DbType = DbType.DateTime,
                    ParameterName = "IsFocusTime",
                    Value = DateTime.Now
                });
                parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "ForumID", Value = id});

            }
            else if (isFocus == "2")
            {
                //去掉其它的聚焦置顶，再设置
                sql = string.Format("update tblPartyForum set IsFocus=1 where IsFocus=2 ;" +
                                    "update tblPartyForum set IsFocus=2,IsFocusTime=?IsFocusTime where ID=?ForumID; ");
                parameters.Add(new MySqlParameter()
                {
                    DbType = DbType.DateTime,
                    ParameterName = "IsFocusTime",
                    Value = DateTime.Now
                });
                parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "ForumID", Value = id});
            }
            else
            {
                sql = string.Format("update tblPartyForum set IsFocus=0,IsFocusTime=null where ID=?ForumID ");
                parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "ForumID", Value = id});
                
            }

            if (MySqlHelper.ExecuteNonQuery(sql, parameters.ToArray()) > 0)
            {
                if (isFocus == "1" )
                {
                    PartyScoreHelper.Add(
                        () => PartyScoreHelper.AddForum(SysEnum.ForumScoreType.Focus, author, createBy, id));
                }
                else if(isFocus=="0")
                {
                    PartyScoreHelper.Add(
                        () => PartyScoreHelper.AddForum(SysEnum.ForumScoreType.CancelFocus, author, createBy, id));
                }
                return true;
            }
            return false;
        }


        /// <summary>
        /// 能否再发帖
        /// </summary>
        /// <returns></returns>
        public static bool CanPostForum(string loginID, DateTime dt, string forumCategory = "")
        {

            var parameters = new List<MySqlParameter>();
            parameters.Add(new MySqlParameter() {DbType = DbType.String, ParameterName = "loginID", Value = loginID});
            parameters.Add(new MySqlParameter() {DbType = DbType.DateTime, ParameterName = "CreateTime", Value = dt});
            var sql = @"SELECT count(1) FROM tblPartyForum pf
                                    where Author=?loginID  and  CreateTime > ?CreateTime ";

            if (!string.IsNullOrEmpty(forumCategory))
            {
                sql += " and ForumCategory=?ForumCategory ";
                parameters.Add(new MySqlParameter()
                {
                    DbType = DbType.String,
                    ParameterName = "ForumCategory",
                    Value = forumCategory
                });
            }
            object obj = MySqlHelper.ExecuteScalar(sql, parameters.ToArray());
            if (obj!=DBNull.Value && obj != null)
            {
                return Convert.ToInt32(obj) < 1;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 版块统计
        /// </summary>
        /// <returns></returns>
        public static void RunForumTypeStatistics()
        {
            try
            {

                var sql = " call Sp_ForumTypeStatistics();";
                MySqlHelper.ExecuteNonQuery(sql);
            }
            catch (Exception ex)
            {
                Log4netHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 个人数据统计
        /// </summary>
        /// <returns></returns>
        public static void RunForumUserInfoStatistics(string loginId)
        {
            try
            {
                var parameters = new List<MySqlParameter>();
                parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "loginId", Value = loginId });
                var sql = " call Sp_ForumUserInfoStatistics(?loginId);";
                MySqlHelper.ExecuteNonQuery(sql, parameters.ToArray());
            }
            catch (Exception ex)
            {
                Log4netHelper.WriteLog(ex);
            }
        }
        #endregion


    }
}
